package com.yss.sofa.report.engine.cell.invisible.dataset;

import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yss.sofa.framework.services.ServiceFactory;
import com.yss.sofa.framework.services.report.ReportCustomData;
import com.yss.sofa.framework.services.report.ReportCustomDataSet;
import com.yss.sofa.report.engine.Const;
import com.yss.sofa.report.engine.Context;
import com.yss.sofa.report.engine.DataSet;
import com.yss.sofa.report.engine.DataSetData;
import com.yss.sofa.report.engine.cell.ReportCell;
import com.yss.sofa.report.engine.cell.invisible.InvisibleCell;

public class OsgiDataSetCell extends InvisibleCell implements DataSet{
	private static final long serialVersionUID = -2354331327086179513L;
	private static final Logger LOGGER=LoggerFactory.getLogger(OsgiDataSetCell.class);
	private String clazz;
	private String exec;
	private Set<String> params=new HashSet<String>();
	protected void init() {
		super.init();
		this.type=Const.REPORT_CELL_TYPE_OSGI_DATASET;	
		this.exec="true";
	}
	public void assignTo(ReportCell cell){
		OsgiDataSetCell _=(OsgiDataSetCell)cell;
		super.assignTo(_);
		_.clazz=this.clazz;
		_.exec=this.exec;
		_.params.clear();
		_.params.addAll(this.params);
	}
	public OsgiDataSetCell create(){
		OsgiDataSetCell _=new OsgiDataSetCell();
		this.assignTo(_);
		return _;
	}
	public String getClazz() {
		return clazz;
	}
	public void setClazz(String clazz) {
		this.clazz = clazz;
	}
	public Set<String> getParams() {
		return params;
	}
	public void setParams(Set<String> params) {
		this.params = params;
	}
	public DataSetData execute(String classname,Context context,Map<String,Serializable> paramsmap,Map<String,String> consts) throws Exception {
		try {
			Map<String,String> filter=new HashMap<String, String>();
			filter.put("class", clazz);
			ReportCustomDataSet dataset=ServiceFactory.getInstance().getService(ReportCustomDataSet.class,filter);
			Map<String,Serializable> values=new HashMap<String, Serializable>();
			for(String key:params){
				values.put(key, paramsmap.get(key));
			}
			values.put("CONSTS", (HashMap<String, String>)consts);
			LOGGER.info("调用报表自定义数据集["+dataset.getClass().getCanonicalName()+"]");
			ReportCustomData externalData=dataset.execute(values);
			if(externalData==null){
				throw new Exception("OSGI数据集["+code+"]的返回结果为null");
			}
			DataSetData data=new DataSetData(externalData);
			if(data.size()>10000){
				LOGGER.warn("OSGI数据集["+code+"]返回的数据已超过10000条");
			}
			return data.convert();
		} catch (Exception e) {
			throw new Exception("OSGI数据集["+code+"]执行失败",e);
		}
	}
	public String getExec() {
		return exec;
	}
	public void setExec(String exec) {
		this.exec = exec;
	}
}
